<template>
    <view>
        <!-- subpackage/roomDetail/roomDetail.wxml -->
        <!-- 自定义导航栏 -->
        <custom-navbar :showTitle="true" backgroundColor="transparent" textColor="#ffffff" :showBack="true"
            :isHomePage="true"></custom-navbar>
        <scroll-view :scroll-y="true" :style="{ height: contentHeight + 'px', position: 'absolute', top: 0, left: 0 }">
            <view class="container">
                <!-- 主要内容区域 -->
                <view class="main" :style="'height: calc(100vh - 172rpx);margin-bottom: ' + tabBarHeight + 'px;'">
                    <!-- 主背景图片区域 -->
                    <swiper class="main-bg">
                        <swiper-item class="main-bg-item">
                            <image class="main-bg-image" src="https://image.shengxuankj.com/fronts/roomDetailBg.png"
                                mode="aspectFill" style="width: 100%; height: 100%"></image>
                        </swiper-item>
                    </swiper>
                    <view class="main-content">
                        <view class="main-content-title">
                            <text>{{ roomDetail.name }}</text>
                            <view class="main-content-title-icon">
                                <image src="https://image.shengxuankj.com/fronts/site_icon.png" mode="" @tap="goToMap"/>
                                <image src="https://image.shengxuankj.com/fronts/phone_icon.png" mode="" @tap="goToCall"/>
                            </view>
                        </view>
                        <view class="main-content-description">{{ roomDetail.desc }}</view>
                        <view class="main-content-service">
                            <view class="main-content-service-item" v-for="(item, index) in roomConfig">
                                <image :src="item.icon" mode="" />
                                <text>{{ item.text }}</text>
                            </view>
                        </view>
                        <view class="main-content-dateView" @tap="openCalendar">
                            <view class="main-content-dateView-item">
                                <text>入住日期</text>
                                <text>{{ checkInDate }}</text>
                            </view>
                            <view class="main-content-dateView-middle">
                                <text>{{ nights }}</text>
                                <text>晚</text>
                            </view>
                            <view class="main-content-dateView-item">
                                <text>入住日期</text>
                                <text>{{ checkOutDate }}</text>
                            </view>
                        </view>
                        <view class="main-content-detail">
                            <view class="main-content-detail-title">详细信息</view>
                            <view class="main-content-detail-facility">
                                <view class="main-content-detail-facility-item" v-for="(item, index) in roomDetail.basic_config" :key="index">
                                    <image :src="item.icon" mode="" />
                                    <text>{{ item.title }}</text>
                                </view>
                                <!-- <text :data-item="item" v-for="(item, index) in roomOtherConfig" :key="index">{{ item.name
                                    }}</text> -->
                            </view>
                            <view class="main-content-detail-list">
                                <view class="main-content-detail-list-item" :data-item="item"
                                    v-for="(item, index) in roomOtherConfig" :key="index">
                                    <text>{{ item.title }}</text>

                                    <text>{{ item.text }}</text>
                                </view>
                            </view>
                        </view>
                        <view class="main-content-notice">
                            <view class="main-content-notice-title">入住须知</view>
                            <view class="roomWxParse">
                                <up-parse :content="richTextContent"></up-parse>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </scroll-view>
        <view class="footer">
            <view class="footer_btn">
                <up-button color="rgba(57, 97, 54, 1)" shape="circle" class="btn" @tap="goToBookPage">立即预订</up-button>
            </view>
        </view>

        <!-- 登录弹窗组件挂载（默认隐藏） -->
        <wx-login-popup :show="showLoginPopup" @close="onCloseLoginPopup" @success="onLoginSuccess" />

        <!-- 日历组件弹窗 -->
        <up-calendar :show="showCalendar" :mode="mode" round="20" startText="住店" endText="离店"
            confirmDisabledText="请选择离店日期" :formatter="formatter" @confirm="selectDate"
            :defaultDate="defaultDateMultiple" @close="closeCalendar" :closeOnClickOverlay="true"></up-calendar>
    </view>
</template>

<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { ref, onMounted } from 'vue'
import customNavbar from '../../components/custom-navbar/index.vue';
import wxLoginPopup from '../../components/wx-login-popup/index.vue';
// subpackage/roomDetail/roomDetail.js
import { roomDetailFun } from '@/api/port'



// 日历相关数据
const showCalendar = ref<boolean>(false)
// 日历相关数据
const mode = ref('range')
const selectedDates = ref<string[]>([])
const defaultDateMultiple = ref<string[]>([])
const closeCalendar = () => {
    showCalendar.value = false
}
const checkInDate = ref<string>('')
const checkOutDate = ref<string>('')
const checkInWeek = ref<string>('')
const checkOutWeek = ref<string>('')
const nights = ref<number>(0)
const calculateNights = () => {
    if (checkInDate.value && checkOutDate.value) {
        const checkIn = new Date(checkInDate.value)
        const checkOut = new Date(checkOutDate.value)
        const diffTime = checkOut.getTime() - checkIn.getTime()
        nights.value = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    }
}
// 选择日期
const selectDate = (dates: string[]) => {
    console.log(dates)
    selectedDates.value = dates
    if (dates.length >= 2) {
        checkInDate.value = dates[0]
        checkOutDate.value = dates[dates.length - 1]
        calculateNights()
        // 计算入住周几
        const checkInDay = new Date(checkInDate.value)
        checkInWeek.value = checkInDay.toLocaleString('zh-CN', { weekday: 'long' })
        // 计算离店周几
        const checkOutDay = new Date(checkOutDate.value)
        checkOutWeek.value = checkOutDay.toLocaleString('zh-CN', { weekday: 'long' })
        console.log(checkInDate.value, checkOutDate.value)
    }
    closeCalendar()
}
// 打开日历弹窗
const openCalendar = () => {
    showCalendar.value = true
}
// 首次进入页面获取默认日期，今天为入住日期，明天为离店日期，并为日历设置默认日期
const getDefaultDate = () => {
    if (checkInDate.value && checkOutDate.value) {
        calculateNights()
    } else {
        const today = new Date()
        const tomorrow = new Date(today)
        tomorrow.setDate(tomorrow.getDate() + 1)
        checkInDate.value = today.toISOString().split('T')[0]
        checkOutDate.value = tomorrow.toISOString().split('T')[0]
        calculateNights()
    }
    // 计算入住周几
    const checkInDay = new Date(checkInDate.value)
    // 计算离店周几
    const checkOutDay = new Date(checkOutDate.value)
    checkInWeek.value = checkInDay.toLocaleString('zh-CN', { weekday: 'long' })
    // 计算离店周几
    checkOutWeek.value = checkOutDay.toLocaleString('zh-CN', { weekday: 'long' })
    // 为日历设置默认日期
    defaultDateMultiple.value = [checkInDate.value, checkOutDate.value]
    console.log(defaultDateMultiple.value)
}


// 响应式数据
const contentHeight = ref<number>(0)
const showLoginPopup = ref<boolean>(false)

const facilityList = ref<any[]>([])

const list = ref<any[]>([])

const richTextContent = ref<string>(`<div>
          <p>民宿退订规则:</p>
          <p style="margin-bottom: 15px;">距离入住日期5天以上(不含5天)可以免费取消预定或者延期。距离入住日期5天以内取消的，扣除订单第一晚房费作为违约金。</p>
          
          <p>宠物政策：</p>
          <p>分享时机，在不同的时机分析用户是否有分享的意愿，提供给他们合适的分享内容，能让分享的效果更好。</p>
          <p style="margin-bottom: 15px;">用户主动点击分享 绝大多数APP都是在详情页等需要分享的页面放置一个分享按钮，由用户自行选择分享。这种情况下用户是否分享主要是取决于产品内容本身，比如内容有趣或是有用。在一些APP中设计者会对这个分享按钮加一些鼓励的文案或着重的设计来促进用户分享。</p>
          
          <p>所以监听用户的截图操作，提示用户进行分享，既缩短了以前分享截图的操作路径，避免了在之前长路径中的行为流失（比如截图完成后忘记分享或觉得麻烦放弃分享等等），也让用户觉得更加贴心。</p>
          <p>下面我们会从不同维度来分析一下APP的社交分享功能设计，看看这里面有哪些值得探讨之处。</p>
          <p style="margin-bottom: 15px;">作为用户和产品之间的桥梁，社交分享在产品的发展过程中扮演了重要的角色。</p>
          
          <p>我们从分享时机、分享形式、分享动机、分享场景4个维度来聊聊「社交分享」的那些事儿。</p>
          <p>尤其...</p>
          </p>
      </div>`)
// 工具函数
const escape2Html = (str: string): string => {
    const arrEntities: { [key: string]: string } = {
        'lt': '<',
        'gt': '>',
        'nbsp': ' ',
        'amp': '&',
        'quot': '"'
    }
    return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, (all, t) => {
        return arrEntities[t]
    })
}

// 计算主要内容区域的高度
const calculateContentHeight = (): void => {
    const systemInfo = uni.getWindowInfo()
    const windowHeight = systemInfo.screenHeight
    const navHeight = uni.getStorageSync('navHeight') ? uni.getStorageSync('navHeight') : 88
    const calculatedContentHeight = windowHeight
    contentHeight.value = calculatedContentHeight
}

// 统一登录判断
const ensureLogin = (): boolean => {
    const app = getApp()
    console.log(app)
    const isLogin = app?.globalData?.token || uni.getStorageSync('token')
    if (!isLogin) {
        showLoginPopup.value = true
        return false
    }
    return true
}

// 关闭登录弹窗
const onCloseLoginPopup = (): void => {
    showLoginPopup.value = false
}

// 登录成功回调
const onLoginSuccess = (e: LoginEvent): void => {
    showLoginPopup.value = false
    // 登录完成后继续预订流程
    goToBookFun()
}

// 预订按钮点击事件（带登录判断）
const goToBookPage = (): void => {
    if (!ensureLogin()) {
        return
    }
    goToBookFun()
}

// 实际跳转预订页逻辑
const goToBookFun = (): void => {
    // 构造房间数据
    const obj: any = {
        room_id: roomDetail.value.id,
        check_in: checkInDate.value,
        check_out: checkOutDate.value,
        num: roomDetail.value.number,
        price: roomDetail.value.price
    }
    console.log(obj)
    uni.navigateTo({
        url: `/subpackage/book/book?orderParmas=${encodeURIComponent(JSON.stringify(obj))}`
    })
}
const roomDetail = ref<any>({})
const roomConfig = ref<any>([])
const roomOtherConfig = ref<any>([])
const getRoomDetailFun = async (params) => {
    const res = await roomDetailFun(params)
    if(res.code == 1){
        roomDetail.value = res.data
        roomConfig.value = JSON.parse(res.data.config)
        roomOtherConfig.value = JSON.parse(res.data.other_config)
    }
}
const homeStayDetail = ref<any>({})
const goToMap = () => {
    if(homeStayDetail.value.latitude && homeStayDetail.value.longitude){
        uni.openLocation({
            latitude: Number(homeStayDetail.value.latitude),
            longitude: Number(homeStayDetail.value.longitude),
            name: homeStayDetail.value.name,
            address: homeStayDetail.value.address
        })
    }
}
const goToCall = () => {
    if(homeStayDetail.value.phone){
        uni.makePhoneCall({
            phoneNumber: homeStayDetail.value.phone
        })
    }
}

onLoad((options) => {
    checkInDate.value = options.checkInDate
    checkOutDate.value = options.checkOutDate
    getDefaultDate()
    getRoomDetailFun({
        room_id: options.room_id
    })
    homeStayDetail.value = JSON.parse(uni.getStorageSync('homeStayDetail'))
})
// 页面挂载时执行
onMounted(() => {
    calculateContentHeight()
})

</script>
<style>
/* subpackage/roomDetail/roomDetail.wxss */

page {
    background-color: #f5f5f5;
    height: 100vh;
}

.container {
    position: relative;
    height: 100vh;
    display: flex;
    flex-direction: column;
}

.main {
    width: 100%;
    position: relative;
}

.main-bg {
    width: 100%;
    height: 688rpx;
}

.main-bg-item {
    width: 100%;
    height: 100%;
}

.main-bg-item iamge {
    width: 100%;
    height: 100%;
}

.main-content {
    position: absolute;
    top: 600rpx;
    left: 0;
    width: 100%;
    padding: 50rpx 30rpx 120rpx 30rpx;
    box-sizing: border-box;
    background-color: #ffffff;
    border-radius: 60rpx 60rpx 0 0;
}

.main-content-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.main-content-title text {
    /** 文本1 */
    font-size: 40rpx;
    font-weight: bold;
    letter-spacing: 0px;
    line-height: 57.92rpx;
    color: rgba(19, 19, 19, 1);
}

.main-content-title-icon {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 24rpx;
}

.main-content-title-icon image {
    width: 40rpx;
    height: 40rpx;
}

.main-content-description {
    font-size: 28rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 40.54rpx;
    color: rgba(85, 85, 85, 1);
    margin-top: 18rpx;
}

.main-content-service {
    /* width: calc(100% - 52rpx - 52rpx); */
    width: 100%;
    padding: 20rpx 30rpx;
    box-sizing: border-box;
    display: grid;
    grid-template-columns: repeat(4, calc((100% - 164rpx - 60rpx) / 4));
    grid-gap: 20rpx;
    /* grid-template-rows: repeat(2, 1fr); */
    /* display: flex;
    align-items: center;
    justify-content: flex-start; */
    /* margin: 32rpx auto; */
}

.main-content-service .main-content-service-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 10rpx 0;
}

.main-content-service .main-content-service-item image {
    width: 42rpx;
    height: 42rpx;
}

.main-content-service .main-content-service-item text {
    /** 文本1 */
    font-size: 20rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 28.96rpx;
    color: rgba(85, 85, 85, 1);
}

.main-content-dateView {
    width: 100%;
    display: flex;
    height: 128rpx;
    padding: 20rpx 25rpx;
    box-sizing: border-box;
    align-items: center;
    justify-content: space-between;
    border-radius: 8px;
    background: rgba(250, 255, 250, 1);
    border: 2px solid rgba(230, 230, 230, 1);
}

.main-content-dateView .main-content-dateView-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.main-content-dateView .main-content-dateView-item text:nth-child(1) {
    /** 文本1 */
    font-size: 24rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 34.75rpx;
    color: rgba(153, 153, 153, 1);
}

.main-content-dateView .main-content-dateView-item text:nth-child(2) {
    /** 文本1 */
    font-size: 32rpx;
    font-weight: bold;
    letter-spacing: 0px;
    line-height: 46.34rpx;
    color: rgba(85, 85, 85, 1);
    margin-top: 8rpx;
}

.main-content-dateView .main-content-dateView-middle {
    /** 文本1 */
    font-size: 28rpx;
    font-weight: bold;
    color: rgba(19, 19, 19, 1);
}

.main-content-detail {
    width: 100%;
    margin-top: 36rpx;
    margin-bottom: 45rpx;
}

.main-content-detail-title {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    /** 文本1 */
    font-size: 32rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 46.34rpx;
    color: rgba(19, 19, 19, 1);
    margin-bottom: 28rpx;
}

.main-content-detail-facility {
    width: 100%;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-gap: 20rpx;
    margin-bottom: 28rpx;
}
.main-content-detail-facility-item{
    display: flex;
    align-items: center;
    justify-content: flex-start;
    gap: 10rpx 0;
}
.main-content-detail-facility-item image{
    width: 28rpx;
    height: 28rpx;
}

.main-content-detail-facility-item text{
    /** 文本1 */
    font-size: 28rpx;
    font-weight: 400;
    color: rgba(19, 19, 19, 1);
    margin-left: 12rpx;
}
.main-content-detail-list {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: flex-start;
    gap: 28rpx 0;
}

.main-content-detail-list .main-content-detail-list-item {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: flex-start;
    gap: 6rpx 0;
}

.main-content-detail-list .main-content-detail-list-item text:nth-child(1) {
    /** 文本1 */
    font-size: 28rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 40.54rpx;
    color: rgba(19, 19, 19, 1);
}

.main-content-detail-list .main-content-detail-list-item text:nth-child(2) {
    /** 文本1 */
    font-size: 24rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 36rpx;
    color: rgba(85, 85, 85, 1);
}

.main-content-notice {
    width: 100%;
}

.main-content-notice .main-content-notice-title {
    /** 文本1 */
    font-size: 32rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 46.34rpx;
    color: rgba(19, 19, 19, 1);
}

.roomWxParse {
    width: 100%;
    padding: 0 30rpx 100rpx 30rpx;
    box-sizing: border-box;
    margin-top: 24rpx;
    /** 文本1 */
    font-size: 28rpx;
    font-weight: 400;
    letter-spacing: 0px;
    line-height: 44rpx;
    color: rgba(85, 85, 85, 1);
}

.footer {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 172rpx;
    padding: 24rpx 30rpx 0 34rpx;
    box-sizing: border-box;
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
}

.footer_btn {
    width: 100%;
    height: 80rpx;
    margin-left: 24rpx;
}

.footer_btn .btn {
    width: 100%;
    height: 100%;
    margin: 0 !important;
}
</style>
